<template>
<el-drawer :title="formDrawer.title" :visible.sync="formDrawer.visible" size="50%" direction="rtl" custom-class="drawer-right-side" :before-close="closeDrawer" :append-to-body="true">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-position="top" class="ruleForm">
        <el-form-item label="跟进状态" prop="status">
            <el-select v-model="ruleForm.status" placeholder="请选择跟进状态" class="w100">
                <el-option v-for="(item,key) in statusList" :key="key" :label="item.title" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item label="无效原因" v-if="ruleForm.status == 6" prop="invalid" :rules="[{required:true,message:'请选择无效原因'}]">
            <el-select v-model="ruleForm.invalid" placeholder="请选择无效原因">
                <el-option v-for="item in invalidList" :key="item.id" :label="item.title" :value="item.id"></el-option>
            </el-select>
        </el-form-item>

        <el-form-item v-if="isShowNextVisit" label="下次回访时间" prop="next_visit_time" :rules="{required: true,message: '请选择下次回访时间',trigger: 'change'}">
            <el-date-picker class="w100" type="datetime" v-model="ruleForm.next_visit_time" placeholder="请选择下次回访时间" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" type="textarea" placeholder="备注"></el-input>
        </el-form-item>

        <el-form-item label="附件">
            <el-upload ref="uploadRef" :action="uploadAction" :headers="uploadHeader" :show-file-list="true" :file-list="fileList" list-type="text" :on-success="uploadSuccess" :on-remove="handleRemove">
                <el-button size="small" type="primary" icon="el-icon-link">附件</el-button>
            </el-upload>
        </el-form-item>

        <div class="fixed-bottom" style="width:50vw;">
            <el-button type="primary" size="small" @click="submit">确认并提交</el-button>
        </div>
    </el-form>
</el-drawer>
</template>

<script>
import {
    getToken
} from '@/utils/auth';
import {
    editVisitApi,
} from "@/api/customer/visit.js";
import {
    getPickerApi
} from "@/api/system/dictionary/status.js";
import uploadFiles from '@/components/upload/files.vue';

const ruleForm = {
    id: '',
    member_id: '',
    status: "",
    invalid: "",
    next_visit_time: "",
    files: [],
    remark: ""
};

export default {
    components: {
        uploadFiles,
    },
    inject: {
        pageIndex: {
            default: () => null
        },
        customerDetail: {
            default: () => null
        }
    },
    data() {
        return {
            formDrawer: {
                title: "添加回访",
                visible: false,
            },
            fileList: [],
            statusList: [],
            ruleForm: Object.assign({}, ruleForm),
            rules: {
                status: [{
                    required: true,
                    message: "请选择跟进状态",
                    trigger: "change",
                }],
                remark: [{
                    required: true,
                    message: "请填写备注",
                    trigger: "blur",
                }],
            },
        };
    },
    computed: {
        isShowNextVisit() {
            let target = this.statusList.find(ele => ele.id == this.ruleForm.status);
            if (!target) return false;

            return target.need_next_visit == 1 ? true : false;
        },
        invalidList() {
            let localData = localStorage.getItem("invalidPickerList");
            if (localData) {
                return JSON.parse(localData);
            } else {
                return [];
            }
        },
        uploadAction: function () {
            return process.env.VUE_APP_BASE_API + "/api/system.file/upload";
        },
        uploadHeader: function () {
            let header = {};
            header["X-Token"] = getToken();
            return header;
        },
    },
    methods: {
        showDrawer(row) {
            this.ruleForm = Object.assign({}, row);
            this.ruleForm.files = row.files;
            this.fileList = row.files;
            console.log(this.ruleForm, this.fileList);
            this.formDrawer.visible = true;
            this.$nextTick(() => {
                // this.$refs["uploadRef"].clearFiles();
            })
            this.getStatusPicker();
        },
        closeDrawer() {
            this.formDrawer.visible = false;
        },
        getStatusPicker() {
            getPickerApi({}).then(res => {
                this.statusList = res.data.list;
            })
        },
        uploadSuccess(res, file) {
            // 获取文件类型;
            // 根据file规则构建新的对象

            const newFile = {
                ext: res.data.extname,
                name: file.name,
                url: res.data.path,
                // 其他属性根据需要添加
            };
            // 将新的文件对象添加到fileList中
            this.fileList.push(newFile);
            // 判断是否是图片类型, 则添加到fileGroup中的image数组中
            this.$emit('input', this.fileList);
        },
        handleRemove(file, fileList) {
            // 提醒确认删除
            this.$confirm("删除文件, 是否继续?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(() => {
                    // 处理移除逻辑...

                    const index = this.fileList.findIndex(item => (file.response && item.url == file.response.data.path) || item.url == file.url);
                    if (index !== -1) {
                        // 删除文件
                        this.fileList.splice(index, 1);
                        this.$emit("input", this.fileList);
                    }
                })
                .catch((e) => {
                    console.log(e);
                    this.$message({
                        type: "info",
                        message: "已取消删除",
                    });
                });
        },
        submit() {
            this.ruleForm.files = this.fileList;
            this.$refs["ruleForm"].validate((valid) => {
                if (!valid) {
                    return false;
                }
                let data = Object.assign({}, this.ruleForm);

                // 添加客资
                editVisitApi(data).then((res) => {
                    if (res.code == "200") {
                        this.$message.success(res.msg);
                        this.customerDetail.getVisitGroup();
                        if (this.pageIndex) this.pageIndex.getTableData();
                        this.closeDrawer();
                    } else {
                        this.$message.warning(res.msg);
                    }
                });
            });
        },
    },
};
</script>
